package com.googlecode.flealancemarket.service.facades.impl;

import com.googlecode.flealancemarket.metamodel.Employer;
import com.googlecode.flealancemarket.metamodel.Freelancer;
import com.googlecode.flealancemarket.metamodel.User;
import com.googlecode.flealancemarket.metamodel.beans.UserBean;
import com.googlecode.flealancemarket.service.facades.UserFacade;
import java.util.List;
import javax.swing.JOptionPane;
import org.hibernate.Criteria;
import org.hibernate.Session;
import org.hibernate.criterion.Example;
import org.hibernate.criterion.MatchMode;
import org.hibernate.criterion.Property;
import org.hibernate.criterion.Restrictions;
import org.springframework.orm.hibernate3.support.HibernateDaoSupport;
import org.springframework.transaction.annotation.Transactional;

public class UserFacadeImpl extends HibernateDaoSupport implements UserFacade {

    @Transactional
    public User saveUser(User u) {
        Session s = getSessionFactory().getCurrentSession();
        long id = (Long) s.save(u);
        u.set_id(id);
        return u;
    }

    @Transactional
    public User loginUser(User u) {
        Session s = getSessionFactory().getCurrentSession();
        
        String strPass = u.getPassword();
        String strUsername = u.getUsername();
        
        User user = (User) s
                            .createCriteria(User.class)
                            .add(Restrictions.like("password", strPass))
                            .add( Restrictions.ilike( "username", strUsername ) )
                            .uniqueResult();
        return user;
    }

    @Transactional
    public List<User> getUserByExample(User example){
        Session session = getSessionFactory().getCurrentSession();
        List<User> users = (List<User>)session
                                .createCriteria(User.class)
                                .add(Restrictions.ilike("username", example.getUsername(), MatchMode.EXACT))
                                .list();
        return users;
    }

    @Transactional
    public User getFullUserById(Long id){
        Session session = getSessionFactory().getCurrentSession();

        Employer emp = (Employer)session
                                .createCriteria(Employer.class)
                                .add(Restrictions.eq("_id", id))
                                .uniqueResult();
        if(emp!=null)
            return emp;

        Freelancer freelancer = (Freelancer)session
                                   .createCriteria(Freelancer.class)
                                    .add(Restrictions.eq("_id", id))
                                    .uniqueResult();
        return freelancer;
    }

}
